var d;
var demo;
// var ue=UE.getEditor('edi
$(function() {
  //开启全屏
  fullDialogModal();

  //开启验证
  demo = $("#editForm").Validform({
    tiptype: 3
  });

    

    laydate.render({
        trigger:'click',
        elem: '#start' //指定元素
    });
    laydate.render({
        trigger:'click',
        elem: '#end' //指定元素
    });

  laydate.render({
        type:'datetime',
        trigger:'click',
        elem: '#listen_time' //指定元素
    });
    
    //开启验证
    demo = $("#editForm").Validform({
        tiptype: 3
    });
    addDialogButton("保存",saveAttend);
    addDialogButton("提交",submitAttend);

    $('#document-file').change(function(){
        uploadFile();
    });

//选择下拉框
  $('.teacher_name').searchableSelect();
  $('.teacher_title').searchableSelect();  
  $('.teachers_attribute').searchableSelect();
  $('.class_type').searchableSelect();
  $('.class_name').searchableSelect();


  $("#teacher_title").next().find('.searchable-select-item').click(function() {
     $("#teacher_title").next().find('.searchable-select-item').removeClass("selected");
        $(this).addClass("selected");
  });

 $("#teachers_attribute").next().find('.searchable-select-item').click(function() {
     $("#teachers_attribute").next().find('.searchable-select-item').removeClass("selected");
        $(this).addClass("selected");
  });

 $("#teachers_attribute").next().find('.searchable-select-item').click(function() {
     $("#teachers_attribute").next().find('.searchable-select-item').removeClass("selected");
        $(this).addClass("selected");
  });

});

//保存
var saveAttend = function(){ 
    save(1);
}


//提交
var submitAttend = function(){
  var msg = "确认是否提交?提交后无法修改";
  swal({
    title: "请确认",
    text: msg,
    type: "warning",
    showCancelButton: true,
    closeOnConfirm: true,
    confirmButtonText: "确定",
    cancelButtonText: '取消',
    confirmButtonColor: "#ec6c62"
  }, function(isConfirm) {
    if(isConfirm) {
        save(2);
      // $.ajax({
      //   type: "post",
      //   url: "Admin/Attend/reply/"+trData.id,
      //   async: true,
      //   success: function(data) {
      //     var ret = $.parseJSON(data);
      //     if(ret.status) {
      //       window.parent.topMessagePrompt('success',ret.msg);
      //                 window.parent.refreshTable();
      //     } else {
      //       window.parent.topMessagePrompt('error',ret.msg);
      //     }
      //   }
      // });
    }
  });
}


//获取教师信息
function gotoSearch(){
  var  teacher_array = $('.teacher_name').val();
      if(teacher_array != 0){
         var strs = new Array(); //定义一数组
         strs = teacher_array.split(","); 

          var teacher_code = strs[0];
          var teacher_name = strs[1];
          
          $.ajax({
            url: 'Admin/Class_Assess/getTeatcherList',
            type: 'POST',
            dataType: 'json',
            data: {
                teacher_code: teacher_code,teacher_name:teacher_name
            },
            success:function(data){
                var v=JSON.parse(data.v);
                if(data.status){
                 //   console.log(v);               
                    $("#teacher_id").val(v['usercode']);
                    $('#dept_name').val(v['dept_name']);
                    if(v['age']){
                         $('#age_groups').val(v['age']);
                    }else{
                         $('#age_groups').val('无');
                    }

                    

                    //赋值教师职称
                    $('#teacher_title').val(v['title']);
                    $("#teacher_title").next().find(".searchable-select-holder").html(v['title']);

                    var strTitle = $("#teacher_title").next().find(".searchable-select-item").text();
                     var TitleArr = new Array(); //定义一数组
                     TitleArr = strTitle.split(" "); 

                    $.each(TitleArr, function(k,arr) {
                        if(arr == v['title']){
                           // console.log('aaa');
                             $("#teacher_title").next().find('.searchable-select-item').eq(k).addClass("selected");
                        }else{
                             //  console.log('bbb');

                             $("#teacher_title").next().find('.searchable-select-item').eq(k).removeClass("selected");
                               $("#teacher_title").next().find('.searchable-select-item').eq(k).removeClass("hover");

                        }
       
                    });
  
                    //教师属性
                    $('#teachers_attribute').val(v['teachers_attribute']);
                     $("#teachers_attribute").next().find(".searchable-select-holder").html(v['teachers_attribute']);
                     var strTitle1 = $("#teachers_attribute").next().find(".searchable-select-item").text();
                     var TitleArr1 = new Array(); //定义一数组
                     TitleArr1 = strTitle1.split(" "); 

                    $.each(TitleArr1, function(k,arr1) {
                        if(arr1 == v['teachers_attribute']){
                           // console.log('aaa');
                             $("#teachers_attribute").next().find('.searchable-select-item').eq(k).addClass("selected");
                        }else{
                              // console.log('bbb');

                             $("#teachers_attribute").next().find('.searchable-select-item').eq(k).removeClass("selected");
                               $("#teachers_attribute").next().find('.searchable-select-item').eq(k).removeClass("hover");

                        }
       
                    });
                       //课程名称
                       getClasslist(teacher_code);    



                     // var class_name2 = $("#class_name2").val();
                     //  if(class_name2 != ""){
                     //      $('.select-style').addClass("hide");
                     //      $('.input-style').removeClass("hide");

                     //      $("#class_name1").removeAttr("dataType");
                     //      $("#class_name2").attr("dataType","*");

                     //      $("#class_name2").removeAttr('disabled');
                     //      $("#class_name1").attr("disabled",true);
                     //       $('#class_name3').val("");
                     //  }else{
                          

                     //     //隐藏输入框
                     //     $('#class_name2').val("");
                     //      $('.select-style').removeClass("hide");
                     //      $('.input-style').addClass("hide");

                     //      $("#class_name2").removeAttr("dataType");
                     //      $("#class_name1").attr("dataType","*");

                     //      $("#class_name1").removeAttr('disabled');
                     //      $("#class_name2").attr("disabled",true); 

                     //  }
                             
                                  
                }else{
                    $("input[name='class_id']").val('0');
                }
            }
        })
        
    }
}

 
//获取老师的课程信息
function getClasslist(teacher_code){
    var class_name3 = $("#class_name3").val();
     $.ajax({
            url:'Admin/Class_Assess/getClassList',
            type: 'POST',
            dataType: 'json',
            data: {
                teacher_code:teacher_code
            },
            success:function(data){
                var t=JSON.parse(data.v);
                if(data.status){
                    var html='';
                    if(t.length >0 ){
                         html ='<option value="0">请选择...</option>';                 
                        $.each(t, function(k, v) {         
                              $("#class_name4").val('3');        
                          if(class_name3 == v['name']){                          
                              $("#class_name4").val(1);
                             html+='<option value="'+v['name']+'" selected ="selected">【'+v['name']+'】 '+v['username']+' --'+v['dept_name']+'</option>';                                                      
                          }else{
                               
                             html+='<option value="'+v['name']+'">【'+v['name']+'】 '+v['username']+' --'+v['dept_name']+'</option>';
                          }                          
                        });
                    
                    }else{
                          html ='<option value="无">无</option>';       
                    } 
                       getShow();
                    
                    $(".class_name").html(html);
                    $(".select-style").find(".searchable-select").remove();
                   $('.class_name').searchableSelect();
                }
            }
        }) 



      // if(class_name3 != ""){
      //     $('.select-style').addClass("hide");
      //     $('.input-style').removeClass("hide");

      //     $("#class_name1").removeAttr("dataType");
      //     $("#class_name2").attr("dataType","*");

      //     $("#class_name2").removeAttr('disabled');
      //     $("#class_name1").attr("disabled",true);
      // }
}

function getShow(){
  var class_name4 = $("#class_name4").val();
  if(class_name4 == 1 || class_name4 == 3){

      alert(1);
        //隐藏输入框
      $('#class_name2').val("");
      $('.select-style').removeClass("hide");
      $('.input-style').addClass("hide");

      $("#class_name2").removeAttr("dataType");
      $("#class_name1").attr("dataType","*");

      $("#class_name1").removeAttr('disabled');
      $("#class_name2").attr("disabled",true); 

  }

   if(class_name4 == 2){
      alert(2);

        $('.select-style').addClass("hide");
          $('.input-style').removeClass("hide");

          $("#class_name1").removeAttr("dataType");
          $("#class_name2").attr("dataType","*");

          $("#class_name2").removeAttr('disabled');
          $("#class_name1").attr("disabled",true);
  }


}


 // 点击搜索列表值，赋值到input上
function getValue(){
    var  class_array = $('.class_name').val();
    var  teacher_array = $('.teacher_name').val();

    if(class_array != 0){
        var strs = new Array(); //定义一数组
         strs = teacher_array.split(","); 

          var teacher_code = strs[0];
          var teacher_name = strs[1];

         $.ajax({
            url: 'Admin/Class_Assess/setClass',
            type: 'POST',
            dataType: 'json',
            data: {
                class_name: $('.class_name').val(),teacher_code:teacher_code
            },
            success:function(data){
                var t=JSON.parse(data.v);
                if(data.status){
                    $('#class_id').val(t['class_id']);
                     $('#attend4').val(t['classname']);
                     $('#course_units').val(t['course_units']);
                     
                  //课程类型
                    $('#class_type').val(t['classtype']);
                     $("#class_type").next().find(".searchable-select-holder").html(t['classtype']);

                     var strTitle1 = $("#class_type").next().find(".searchable-select-item").text();
                     var TitleArr1 = new Array(); //定义一数组
                     TitleArr1 = strTitle1.split(" "); 
                  //   console.log(TitleArr1);

                    $.each(TitleArr1, function(k,arr1) {
                     // console.log(arr1);console.log(t['classtype']);
                        if(arr1 == t['classtype']){
                          //  console.log('aaa');
                             $("#class_type").next().find('.searchable-select-item').eq(k).addClass("selected");
                        }else{
                            //  console.log('bbb');

                             $("#class_type").next().find('.searchable-select-item').eq(k).removeClass("selected");
                             $("#class_type").next().find('.searchable-select-item').eq(k).removeClass("hover");

                        }
       
                    });
                }else{
                    window.parent.topMessagePrompt('error',data.msg);
                }
            }
        }) 
    }
    
}



// 实时计算打分情况
function levelsum(){
    var sum=0;
    $.each($("#step3 .margin-bottom input[type='text']"), function(k, v) {
        // console.log(v);
        var id=this.id;
        var val=$('#'+id).val();
        if(val!='' ){
            val=parseInt(val);
            sum+=val;
        }            
    });
    $(".teaching_level_sum").html('当前总分为：'+sum);
}
function effectsum(){
    var sum=0;
    $.each($("#step4 .margin-bottom input[type='text']"), function(k, v) {
        // console.log(v);
        var id=this.id;
        var val=$('#'+id).val();
        if(val!='' ){
            val=parseInt(val);
            sum+=val;
        }            
    });
    $(".teaching_effect_sum").html('当前总分为：'+sum);
}


// 输入上课班级查询指定课程数据
function checkClass(){
    var teacher_id=$("#teacher_id").val();
    // 上课班级
    var classname=$("#attend4").val();
    // 课程名称
    var name=$("#class_name1").val();
    $.ajax({
        url: 'Admin/Class_Assess/checkClass',
        type: 'POST',
        dataType: 'json',
        data: {
            teacher_id: teacher_id,
            classname:classname,
            name:name
        },
        success:function(data){
            var t=JSON.parse(data.v);
            if(data.status){
                $("input[name='class_type']").val(t.type);
                $("#class_type").html(t.type);
                $("input[name='course_units']").val(t.course_units);
                $("input[name='class_id']").val(t.id);
            }
        }
    })
}

// 获取教师信息
// function getTeacherInfo(){
//     var teacher_code=$("#teacher_name").val();
//     $.ajax({
//         url: $('input[name="url"]').val()+'Admin/Class_Assess/getTeacherInfo',
//         type: 'POST',
//         dataType: 'json',
//         data: {
//             teacher_code: teacher_code
//         },
//         success:function(data){
//             var t=JSON.parse(data.v);
//             if(data.status){
//                 console.log(t);
//                 // $("")
//             }else{
//                 $("input[name='class_id']").val('0');
//             }
//         }
//     })
// }

function save(status){
  if (!demo.check()) {
    $('.Validform_error:first').focus();
    return;
  }
  if($('.select-style').hasClass('hide') == false && $('.select-style').find('option:selected').val() == 0){
    // select显示
    swal({
        title: "提示",
        text: '请选择课程',
        type: "warning",
        showCancelButton: false,
        closeOnConfirm: true,
        confirmButtonText: "确定",
        confirmButtonColor: "#ec6c62"
    });
    return false;
  }

   if($('.input-style').hasClass('hide') == false && $('.input-style').val() == ''){
    swal({
        title: "提示",
        text: '请选择课程',
        type: "warning",
        showCancelButton: false,
        closeOnConfirm: true,
        confirmButtonText: "确定",
        confirmButtonColor: "#ec6c62"
    });
    return false;
  }


    d = dialog({
        title: '',
        content: "数据保存中,请稍后...",
    });
    d.showModal();

    
   console.log(status);

       var attend1 = $("#attend1").val();
        var attend2 = $("#attend2").val();
        var attend3 = $("#attend3").val();
        var attend4 = $("#attend4").val();
        var attend5 = $("#attend5").val();

        var class_id =$("#class_id").val();
        var teacher_id =$("#teacher_id").val();
        // console.log($("#class_id"));
        // console.log($("#teacher_id"));
        // return;
        var attend= new Array(class_id,teacher_id,attend1,attend2,attend3,attend4,attend5);
        var teachingLevel1= $('#teachingLevel1').val();
        var teachingLevel2 = $("#teachingLevel2").val();
        var teachingLevel3 = $("#teachingLevel3").val();
        var teachingLevel4 = $("#teachingLevel4").val();
        var teachingLevel5 = $("#teachingLevel5").val();
        var teachingLevel6 = $("#teachingLevel6").val();
        var teachingLevel7 = $("#teachingLevel7").val();
        var teachingLevel8 = $("#teachingLevel8").val();
        var teachingLevel9 = $("#teachingLevel9").val();
        var teachingLevel = new Array(teachingLevel1, teachingLevel2, teachingLevel3, teachingLevel4, teachingLevel5, teachingLevel6, teachingLevel7, teachingLevel8, teachingLevel9);
        var teachingEffect1 = $("#teachingEffect1").val();
        var teachingEffect2 = $("#teachingEffect2").val();
        var teachingEffect3 = $("#teachingEffect3").val();
        var teachingEffect4 = $("#teachingEffect4").val();
        var teachingEffect5 = $("#teachingEffect5").val();
        var teachingEffect6 = $("#teachingEffect6").val();
        var teachingEffect = new Array(teachingEffect1, teachingEffect2, teachingEffect3, teachingEffect4, teachingEffect5, teachingEffect6);
        var teachingReadiness1 = $('input:radio[name="item1"]:checked').val();
        var teachingReadiness2 = $('input:radio[name="item2"]:checked').val();
        var teachingReadiness3 = $('input:radio[name="item3"]:checked').val();
        var teachingReadiness4 = $('input:radio[name="item4"]:checked').val();
        var teachingReadiness5 = $('input:radio[name="item5"]:checked').val();
        var teachingReadiness6 = $('input:radio[name="item6"]:checked').val();
        var teachingReadiness7 = $('input:radio[name="item7"]:checked').val();
        var teachingReadiness8 = $('input:radio[name="item8"]:checked').val();
        var teachingReadiness9 = $('input:radio[name="item9"]:checked').val();
        var teachingReadiness10 = $('input:radio[name="item10"]:checked').val();
        var teachingReadiness11 = $('input:radio[name="item11"]:checked').val();
        var teachingReadiness12 = $('input:radio[name="item12"]:checked').val();
        var teachingReadiness = new Array(teachingReadiness1, teachingReadiness2, teachingReadiness3, teachingReadiness4, teachingReadiness5, teachingReadiness6, teachingReadiness7, teachingReadiness8, teachingReadiness9, teachingReadiness10, teachingReadiness11, teachingReadiness12);
        var studentsNorm1 = $("#studentsNorm1").val();
        var studentsNorm2 = $("#studentsNorm2").val();
        var studentsNorm3 = $("#studentsNorm3").val();
        var studentsNorm4 = (studentsNorm3/studentsNorm1)*100;
        studentsNorm4.toFixed(2);
        studentsNorm4=studentsNorm4+'%';
        $("#studentsNorm4").val(studentsNorm4);        
        var studentsNorm5 = $("#studentsNorm5").val();
        var studentsNorm6 = $("#studentsNorm6").val();
        var studentsNorm7 = $("#studentsNorm7").val();
        var studentsNorm8 = $("#studentsNorm8").val();
        var studentsNorm9 = $("#studentsNorm9").val();
        var studentsNorm = new Array(studentsNorm1, studentsNorm2, studentsNorm3, studentsNorm4, studentsNorm5, studentsNorm6, studentsNorm7, studentsNorm8, studentsNorm9);
        var classroom_facilities = $('input:radio[name="item13"]:checked').val();
        var classroom_environmental = $('input:radio[name="item14"]:checked').val();
        var attend_record = new Array();
        $("#step6_form .write").each(function() {
            attend_record.push($(this).val());
        });
        $("#attend_record").val(attend_record);
        var is_add=$("#is_add").val();   
        var k=0;

        // $("#img").html('');
        // $("li img").each(function(k,v) {
        //     console.log(this);
        //     $("#img").append("<input type='hidden' name='attend_img["+k+"]' class='attend_img' value='"+$(this).attr('src')+"'>");
        //     k++;
        // });
        
        var attend_id=$('#is_add').val()
        console.log(attend_id);
        if(attend_id==0){
            var url='Admin/Class_Assess/saveAttend';
        }else{
           var url='Admin/Class_Assess/saveAttend/'+attend_id;
       }
     //  console.log($("#img .attend_img").val());
       var data=$("form").serialize();
       data=data+"&save="+status;

       $("#submit").attr('disabled',true);
        $("#save").attr('disabled',true);
    $.ajax({
        url:  url,
        type: 'POST',
        dataType: 'json', 
        data:data,
        success: function(data) {
          console.log(data);

            if(d != undefined)
                  d.close().remove();
              var ret = data; //$.parseJSON(data);
              if(ret.status) {
                  var v = $.parseJSON(ret.v);
                  if(v == 1) {
                      window.parent.refreshTable();
                      showDialogModalConfirm(
                          'success',
                          '保存成功！',
                          ret.msg,
                          '继续添加',
                          '返回列表',
                          function(){
                              $("form")[0].reset();
                          },
                          function(){
                              hideDialogModal();
                          });
                  } else {
                      window.parent.topMessagePrompt('success',ret.msg);
                      window.parent.refreshTable();
                      hideDialogModal();
                  }

              } else {
                  window.parent.topMessagePrompt('error',ret.msg);
              }
        }
    })
}



function checkRole(){
    $.ajax({
            url: 'Admin/Class_Assess/checkSubrole',
            type: 'POST',
            dataType: 'json',
            async:false,
            success:function(data){
                if(data.status){
                    var t=JSON.parse(data.v);
                    if(t['html']){
                        dialog1 = jqueryAlert({
                            'style': 'wap',
                            'title': '请选择提交反馈身份',
                            'content': t['html'],
                            'modal': true,
                            'contentTextAlign': 'center',
                            'width': '300',
                            'height': '120',
                            'animateType': 'linear',
                            'buttons': {
                               
                                '确定':function(){
                                   if($("#sub_role").val()=='0'){
                                        var dialog2 = jqueryAlert({
                                        'icon': $('input[name="url"]').val() + 'public/home/alert/img/error.png',
                                        'content': '请选择反馈身份！',
                                        'closeTime': 1000,
                                    })
                                   }else{
                                        dialog1.close();
                                        $('input[name="sub_role"]').val($("#sub_role").val());
                                   }
                                   
                               }
                           }
                       })
                    }
                }
            }
        })
}


var now_type = '';

function uploadDocument(obj) {
    now_type = $(obj).attr('data-type');
    $('#document-file').click();
}

function uploadFile() {
    
    var fileObj = document.getElementById("document-file").files; // js 获取文件对象
    if(fileObj.length==0){
        errorAlert('请选择图片');
        return;
    }
    var formFile = new FormData();
    for (var i = 0; i <fileObj.length; i++) {
        formFile.append("myfile[]", fileObj[i]); //加入文件对象
    }
    $('.document-p .progress-bar').css('width', '0%');
    $('.document-p .p-text').html('已上传（0%）');
    $('.document-p').show();
    var data = formFile;
    setTimeout(function() {
        $.ajax({
            url: 'Admin/CommonUpload/upload/' + now_type,
            data: data,
            type: "POST",
            dataType: "json",
            cache: false, //上传文件无需缓存
            processData: false, //用于对data参数进行序列化处理 这里必须false
            contentType: false, //必须
            xhr: xhrOnProgress(function(e) {
                var percent = e.loaded / e.total;
                var now_jindu = (parseFloat(percent) * 100).toFixed(2);
                console.log(now_jindu);
                $('.document-p .progress-bar').css('width', now_jindu + '%');
                $('.document-p .p-text').html('已上传（' + now_jindu + '%）');
                $('.document-p').show();
            }),
            success: function(data) {
                $('.document-p .progress-bar').css('width', '100%');
                $('.document-p .p-text').html('已上传（100%）');
                $('.document-p').hide();
                if (data.status) {
                    // alert(now_type);
                    var path=JSON.parse(data.v);
                    var icon=JSON.parse(data.remark);
                    $.each(path,function(k,v){
                       $('.data-box-demo img').attr('src', getRootPath() + '/' + v);
                       $('.data-box-demo a').attr('href', getRootPath() + '/' +v);
                       $('.data-box-demo .path').val(v).attr('name', 'attend_img[' + now_type + '][]');
                      //  $('.data-box-demo img').attr('src', getRootPath() + '/' + v);
                      //  $('.data-box-demo a').attr('href', getRootPath() + '/' +v);
                       // $('.data-box-demo .path').val(getRootPath() + '/' +v).attr('name', 'attend_img[' + now_type + '][]');
                      //  $('.data-box-demo .icon').val(icon[k]).attr('name', 'icon[' + now_type + '][]');
                        $('#editForm .td_' + now_type).append($('.data-box-demo').html());
                    }); 
                } else {
                    window.parent.topMessagePrompt('error', data.msg);
                }
            }
        })
    }, 1000);
}

var xhrOnProgress = function(fun) {
    xhrOnProgress.onprogress = fun; //绑定监听
    //使用闭包实现监听绑
    return function() {
        //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
        var xhr = $.ajaxSettings.xhr();
        //判断监听函数是否为函数
        if (typeof xhrOnProgress.onprogress !== 'function')
            return xhr;
        //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
        if (xhrOnProgress.onprogress && xhr.upload) {
            xhr.upload.onprogress = xhrOnProgress.onprogress;
        }
        return xhr;
    }
}
function delDocument(obj) {
    var path = $(obj).parent('.data-box').find('.path').val();
    $(obj).parent('.data-box').remove();
    // $.ajax({
    //     url: "Admin/CommonContract/delDocument",
    //     type: "post",
    //     data: {
    //         path: path
    //     },
    //     dataType: 'json',
    //     success: function(data) {
    //         if (data.status) {

    //         } else {

    //         }
    //     }
    // });
}
// 大图预览
function showImage(obj) {
    var img = { data: [] }
    $(obj).parent().parent().parent().find('.path').each(function() {
        // alert($(this).next().val());
        if ($(this).next().val() == 'img.png') {
            img.data.push({ 'alt': '', 'pid': (Number($(this).index()) + 1), 'src': $(this).val(), 'thumb': '' });
        }
    });
    if (img.data.length == 0) {
        window.parent.topMessagePrompt('error', '无图片');
    } else {
        showDialogModalPhoto(img);
    }
}




function delImg(obj){
    $(obj).prev().prev().attr('src','cust/images/upload.png');
    $(obj).prev().prev().prev().val('');
}
function showProduct(obj){
    window.open($(obj).attr('data-href'));
}



function bannerPrev(obj){
    var can_prev=$(obj).parents('.data-box').prev().hasClass('data-box-banner');
    if(can_prev){
        $(obj).parents('.data-box').prev().before($(obj).parents('.data-box'));
    }
}

function bannerNext(obj){
    var can_next=$(obj).parents('.data-box').next().hasClass('data-box-banner');
    if(can_next){
        $(obj).parents('.data-box').next().after($(obj).parents('.data-box'));
    }
}
